package org.example.nebula.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.vesoft.nebula.client.graph.data.ResultSet;
import com.vesoft.nebula.client.graph.net.Session;
import lombok.extern.slf4j.Slf4j;
import org.example.nebula.common.exception.GlobalExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author: jszhang
 * @date: 2023/2/13-11:09
 */
@Slf4j
@Service
public class CommonService {

    @Autowired
    private Session session;

    public JSONArray executeJson(String gql) {
        try {
//            log.info("执行executeJson方法，GQL={}", gql);
            String data = session.executeJson(gql);
            JSONObject jsonObject = JSONUtil.parseObj(data);

            JSONObject error = jsonObject.getJSONArray("errors").getJSONObject(0);
            int code = error.getInt("code");
            if (code != 0) {
                throw new GlobalExceptionHandler("执行GQL出现错误，GQL=" + gql + "，code=" + code + "，message="
                        + error.getStr("message"));
            }
//            log.info("执行executeJson方法，GQL={}\n查询到{}", gql, jsonObject.getJSONArray("results").getJSONObject(0).getJSONArray("data").size() + "条数据");
            JSONArray results = JSONUtil.parseArray(jsonObject.get("results"));
            return results;
        } catch (Exception e) {
            log.error("执行GQL[{}]出现错误，信息为[{}]", gql, e.getMessage());
            throw new GlobalExceptionHandler("执行GQL出现错误，GQL=" + gql + "，message=" + e.getMessage());
        }
    }

    public ResultSet execute(String gql) {
        try {
//            log.info("执行executeJson方法，GQL={}", gql);
            ResultSet resultSet = session.execute(gql);
            // 如果查询出现问题，抛出异常
            if (!resultSet.isSucceeded()) {
                log.error("执行GQL出现错误，GQL={}，code={}，message={}",gql,resultSet.getErrorCode(),resultSet.getErrorMessage());
                throw new GlobalExceptionHandler("执行GQL出现错误，code=" + resultSet.getErrorCode() + "，message=" + resultSet.getErrorMessage());
            }
            // 如果查询正常，输出查到的数据量
            log.info("执行executeJson方法，GQL={}\n查询到{}", gql, resultSet.rowsSize() + "条数据");
            return resultSet;
        } catch (Exception e) {
            log.error("执行GQL[" + gql + "]出现错误，异常信息为[" + e.getMessage() + "];", e);
            throw new GlobalExceptionHandler("执行GQL出现错误，message=" + e.getMessage());
        }
    }

}
